$(function() {

	let requestUrl = 'https://www.yi-p.com/';
	let vcodeImg = $('#vcodeImg');
	let loginBtn = $('#loginBtn');
	let userNameBox = $('#userNameBox');
	let userPwdBox = $('#userPwdBox');
	let vcodeBox = $('#vcodeBox');
	let errorTip = $('#errorTip');
	let logined = false;

	getVcode();

	function getVcode() {
		let rn = Date.now();
		window.localStorage.setItem('rn', rn);
		vcodeImg.attr({src: 'https://www.yi-p.com/sys/getVcode?rn=' + rn});
	}

	function ajax(url, dataType, data, successFun, errorFun, timeoutFun, timeout, type) {
		dataType = dataType || 'json';
		timeout = timeout || 15000;
		type = type || 'POST';
		$.ajax({
			type: type,
			url: url,
			data: data,
			dataType: dataType,
			timeout: timeout,
			success: successFun,
			error: function(XHR, textStatus, errorThrown) {
				if(textStatus == 'timeout' && timeoutFun) {
					timeoutFun();
				}
				else {
					errorFun(XHR, textStatus, errorThrown);
				}
			}
		});
	}

	function showError(content) {
		errorTip.html(content);
		errorTip.fadeIn(300, function() {
			setTimeout(function() {
				errorTip.fadeOut(300);
			}, 1500);
		});
	}

	function login(userName, userPwd, vcode) {
		loginBtn.html('登录中');
		loginBtn.attr({disabled: true, class: 'disabled'});
		logined = true;
		ajax(requestUrl + 'user/adminLogin', 'json', {
			userName: userName,
			userPwd: userPwd,
			vcode: vcode,
			vcodeRn: window.localStorage.getItem('rn')
		}, function(data) {
			console.log(data);
			if(data.errCode == '0') {
				window.localStorage.setItem('session', data.data);
				window.location.href = './manager.html';
			}
			else {
				switch(data.errCode) {
					case '-0142':
						showError('验证码错误');
						getVcode();
					break;
					case '-0144':
						showError('用户名或密码错误');
						getVcode();
					break;
					default:
						showError('[' + data.errCode + ']登录失败：' + data.errMsg);
				}
				loginBtn.html('登录');
				loginBtn.attr({class: ''});
				loginBtn.removeAttr('disabled');
				logined = false;
			}
		}, function(XHR, textStatus, errorThrown) {
			showError('[' + textStatus + ']登录失败：' + errorThrown);
			loginBtn.html('登录');
			loginBtn.attr({class: ''});
			loginBtn.removeAttr('disabled');
			logined = false;
		}, function() {
			showError('登录超时，请重试');
			loginBtn.html('登录');
			loginBtn.attr({class: ''});
			loginBtn.removeAttr('disabled');
			logined = false;
		});
	}

	vcodeImg.click(function() {
		getVcode();
	});

	loginBtn.click(function() {
		if(logined) {
			return;
		}
		if(userNameBox.val() != '' && userPwdBox.val() != '' && vcodeBox.val() != '') {
			login(userNameBox.val(), userPwdBox.val(), vcodeBox.val());
		}
		else {
			showError('请输入用户名、密码、验证码');
		}
	});

	$(document).keydown(function(e) {
		let key = e.which;
		if(key == 13) {
			loginBtn.click();
		}
	})
})